<template>
  <Modal v-model="status"
         title="人员选择"
         :mask-closable="false"
         footer-hide
         width="700"
         @on-cancel="hide">
    <div>
      <div class="select-area">
        <div class="tree-area">
          <div class="search-box">
            <span class="title"
                  style="width:50px;display:block;">选择：</span>
            <Input v-model="searchName"
                   placeholder="输入姓名搜索"
                   style="margin-right:10px"
                   clearable
                   @on-change="search" />
          </div>
          <div class="tree-box">
            <Tree :data="treeData"
                  ref="JTree"
                  multiple
                  show-checkbox
                  children-key="users"
                  @on-check-change="changeSelect" />
          </div>
        </div>
        <div class="selected-area">
          <span class="title">已选择：</span>
          <div class="selected-list">
            <template v-for="(user,index) in selectUser">
              <div class="selected-box"
                   :key="user.userid">
                <span class="title">{{user.title}}</span>
                <i class="ivu-icon ivu-icon-ios-close-circle"
                   @click="cancelSelect(user,index)" />
              </div>
            </template>
          </div>
        </div>
      </div>

      <div slot="footer"
           class="button-area">
        <Button type="primary"
                @click="confirm">确认</Button>
        <Button @click="cancel">取消</Button>
      </div>
    </div>

  </Modal>
</template>

<script>
import { ajaxPost } from 'global/axios';
import storage from 'good-storage';
import jquery from 'jquery';

export default {
  data() {
    return {
      status: false,
      searchName: '',
      treeData: [],
      selectUser: [],
      selectDep: [],
    };
  },

  mounted() {
    this.getUserList();
  },

  methods: {
    // 展示
    show() {
      this.status = true;
    },

    // 获取人员数据
    getUserList() {
      if (this.selectUser.length > 0) {
        this.selectUser.forEach(item => {
          item.cache = true;
        });
      }
      ajaxPost({
        data: {
          realname: this.searchName ? `${this.searchName}|#|like` : '',
          sub: true
        },
        url: '/sys/userinfo/findbydep',
        token: storage.session.get('token'),
        success: res => {
          let { result } = res.data;
          result.forEach((dep, depIndex) => {
            dep.className = 'dep';
            dep.title = dep.dep_name;
            dep.depIndex = depIndex;
            dep.users.forEach((user, userIndex) => {
              if (this.selectUser.length > 0) {
                let selectedTarget = this.selectUser.find(
                  item => item.userid === user.userid
                );
                selectedTarget && (user.checked = true);
              }
              user.depIndex = depIndex;
              user.userIndex = userIndex;
              user.title = user.realname;
              user.className = 'user';
            });
          });
          this.treeData = result;
          this.$nextTick(() => {
            let selectMap = [];
            let selectUser = [];
            this.$refs.JTree.getCheckedNodes()
              .filter(item => item.className === 'user')
              .forEach(item => {
                selectMap.push(item.userid);
                selectUser.push(item);
              });

            this.selectUser.forEach(item => {
              if (selectMap.indexOf(item.userid) < 0) {
                selectMap.push(item.userid);
                selectUser.push(item);
              }
            });

            this.selectUser = selectUser;
          });
        },
      });
    },

    // 搜索
    search() {
      this.selectDep = [];
      this.treeData = [];
      this.getUserList();
    },

    // 选择切换
    changeSelect(data) {
      let selectMap = [];
      let selectUser = [];
      let selectDep = [];

      data.forEach(item => {
        item.className === 'user' && selectMap.push(item.userid);
        item.className === 'user' && selectUser.push(item);
        item.className === 'dep' && selectDep.push(item);
      });

      this.selectUser.forEach(item => {
        if (selectMap.indexOf(item.userid) < 0 && item.cache) {
          selectUser.push(item);
          selectMap.push(item.userid);
        }
      });

      this.selectUser = selectUser;
      this.selectDep = selectDep;
    },

    // 取消选择
    cancelSelect(item, index) {
      this.selectUser.splice(index, 1);
      if (!item.cache) {
        let { depIndex, userIndex } = item;
        let dep = jquery('.ivu-tree').find('.ivu-tree-children')[depIndex];
        let userList = jquery(dep).find('.ivu-tree-children');
        let user = userList[userIndex];
        jquery(user).find('.ivu-checkbox-wrapper').click();
      }
    },

    // 确认
    confirm() {
      this.$emit('change', this.selectUser);
      this.status = false;
    },

    // 关闭
    hide() {
      this.status = false;
    },

    // 取消
    cancel() {
      this.$refs.JTree.getCheckedAndIndeterminateNodes().forEach(item => {
        item.checked && (item.checked = false);
        item.indeterminate && (item.indeterminate = false);
      });

      this.selectUser = [];
      this.selectDep = [];

      this.$nextTick(() => {
        this.$emit('change', this.selectUser);
        this.status = false;
      });
    },
  },
};
</script>

<style lang="scss" scope>
.select-area {
  display: flex;
  align-items: stretch;
  height: 400px;
  padding: 10px 0 30px;
  box-sizing: border-box;
  > div {
    flex: 1;
    box-sizing: border-box;
  }
  .tree-area {
    border-right: 1px solid #f1f1f1;
    display: flex;
    flex-direction: column;
    align-items: stretch;
    .search-box {
      box-sizing: border-box;
      padding-right: 10px;
      flex: 0 0 auto;
      margin-bottom: 20px;
      display: flex;
      align-items: center;
    }

    .tree-box {
      flex: 1;
      overflow-y: auto;
    }
  }
  .selected-area {
    display: flex;
    align-items: stretch;
    flex-direction: column;
    > .title {
      flex: 0 0 auto;
      display: block;
      height: 32px;
      line-height: 32px;
      padding: 0 16px;
      margin-bottom: 20px;
      box-sizing: border-box;
    }
    .selected-list {
      flex: 1;
      overflow-y: auto;

      .selected-box {
        padding: 5px 20px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .title {
          width: 200px;
          height: 16px;
          line-height: 16px;
          display: block;
          font-size: 12px;
        }
        .ivu-icon {
          width: 16px;
          height: 16px;
          color: red;
          font-size: 16px;
          line-height: 16px;
          display: block;
        }
      }
    }
  }
}
.button-area {
  width: 150px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>